package be.rubengerits.android.car.dashboard.notifications;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.widget.LinearLayout;

public class OverlayObserver extends AsyncTask<String, String, String> {

	private static LinearLayout mOverlayLayout;

	private static List<OverlayEdition> mBackLog = null;

	// index of all overlays
	private static List<Integer> mNotificationList = null;

	private static OverlayObserver instance;

	private final boolean stop = false;

	/* --- singleton access --- */
	public static OverlayObserver getInstance() {
		if (instance == null) {
			instance = new OverlayObserver();
		}

		return instance;
	}

	/* --- functions --- */

	/**
	 * Must be called before anything else can be done
	 * 
	 * @param overlayView
	 */
	public void setup(LinearLayout overlayView) {
		if (mOverlayLayout != null) {
			throw new RuntimeException("NotificationObserver is already initialized");
		}

		mBackLog = new ArrayList<OverlayEdition>();
		mNotificationList = new ArrayList<Integer>();
		mOverlayLayout = overlayView;

		this.execute();
	}

	public void notificationEdition(OverlayEdition overlay) {
		mBackLog.add(overlay);
	}

	private void updateOverlayLayout() throws Exception {
		if (mOverlayLayout != null && mBackLog.size() > 0) {
			OverlayEdition overlayEdition = mBackLog.get(0);

			if (EditionType.ADD_OR_UPDATE.equals(overlayEdition.getEditionType())) {
				addOrUpdateNotification(overlayEdition.getKey(), overlayEdition.getOverlay());
			} else if (EditionType.REMOVE.equals(overlayEdition.getEditionType())) {
				removeNotification(overlayEdition.getKey());
			}
		}
	}

	private void removeNotification(Integer key) throws Exception {
		if (mNotificationList.get(key) == null) {
			throw new Exception("Cannot remove an overlay that doesn't exist.");
		}
	}

	private void addOrUpdateNotification(Integer key, Overlay overlay) throws Exception {
		if (mNotificationList.get(key) == null) {
			// add
		} else {
			// update
		}
	}

	@Override
	protected String doInBackground(String... params) {
		while (true) {
			this.publishProgress("Checking for updates...");

			try {
				this.updateOverlayLayout();
			} catch (Exception e) {
				throw new RuntimeException("Error occured while updating the OverlayLayout", e);
			}

			this.publishProgress("Modifications done...");

			if (stop) {
				break;
			}
		}
		return "OverlayObserver ended...";
	}

}
